<template>
  <el-drawer
    ref="drawerBox"
    v-bind="$attrs"
    :wrapper-closable="false"
    :close-on-press-escape="false"
    :size="showMobilePage?'100%':'80%'"
    class="related-order-drawer"
    append-to-body
    @open.once="onDrawerOpen"
    @closed="onDrawerClosed"
    v-on="$listeners"
  >
    <el-tabs slot="title" v-model="curActiveOrder" :before-leave="() => !listLoading" class="related-order-tabs" @tab-click="onOrderChange">
      <el-tab-pane :name="ACTIVE_ORDERS.CHANNEL" label="渠道订单" />
      <el-tab-pane :name="ACTIVE_ORDERS.PROJECT_CHANNEL" label="项目渠道单" />
      <el-tab-pane :name="ACTIVE_ORDERS.PROJECT" label="项目订单" />
    </el-tabs>
    <div class="drawer-content">
      <filter-input
        ref="FilterToolRef"
        v-model="paramsObj"
        :filter-list="filterList"
        show-search-btn
        line-feed
        @selectChange="handleFilterInputChange"
        @handelClick="queryClick"
        @queryEmpty="queryEmpty"
      />
      <el-tabs
        v-model="curSubActiveOrder"
        :before-leave="() => !listLoading"
        type="card"
        class="tab-content"
        @tab-click="onSubActiveOrderChange"
      >
        <el-tab-pane label="订单列表"/>
        <el-tab-pane>
          <span slot="label">已选择订单<el-badge v-if="getSelectedNum" :value="getSelectedNum" /></span>
        </el-tab-pane>
      </el-tabs>
      <div class="table-list">
        <!--渠道订单-->
        <template v-if="curActiveOrder === ACTIVE_ORDERS.CHANNEL">
          <channel-order
            v-if="curSubActiveOrder === SUB_ACTIVE_ORDERS.ALL_ORDER"
            ref="channelOrder"
            key="channelAllOrder"
            :list="list"
            :list-loading="listLoading"
            :is-selected-order="false"
            select-callback
            @onSelectChange="onSelectChange"
          />
          <channel-order
            v-else
            ref="channelOrder"
            key="channelSelectedOrder"
            :list="list"
            :list-loading="listLoading"
            is-selected-order
            select-callback
            @relatedCancel="relatedCancel"
            @relatedMulCancel="relatedMulCancel"
          />
        </template>
        <!--项目渠道订单-->
        <template v-else-if="curActiveOrder === ACTIVE_ORDERS.PROJECT_CHANNEL">
          <project-channel-order
            v-if="curSubActiveOrder === SUB_ACTIVE_ORDERS.ALL_ORDER"
            ref="projectChannelOrder"
            key="projectChannelAllOrder"
            :list="list"
            :list-loading="listLoading"
            :is-selected-order="false"
            select-callback
            @onSelectChange="onSelectChange"
          />
          <project-channel-order
            v-else
            ref="projectChannelOrder"
            key="projectChannelSelectedOrder"
            :list="list"
            :list-loading="listLoading"
            is-selected-order
            select-callback
            @relatedCancel="relatedCancel"
            @relatedMulCancel="relatedMulCancel"
          />
        </template>
        <!--项目订单-->
        <template v-else-if="curActiveOrder === ACTIVE_ORDERS.PROJECT">
          <project-order
            v-if="curSubActiveOrder === SUB_ACTIVE_ORDERS.ALL_ORDER"
            ref="projectOrder"
            key="projectAllOrder"
            :list="list"
            :list-loading="listLoading"
            :is-selected-order="false"
            select-callback
            @projectOrderSort="projectOrderSort"
            @onSelectChange="onSelectChange"
          />
          <project-order
            v-else
            ref="projectOrder"
            key="projectSelectedOrder"
            :list="list"
            :list-loading="listLoading"
            is-selected-order
            select-callback
            @projectOrderSort="projectOrderSort"
            @relatedCancel="relatedCancel"
            @relatedMulCancel="relatedMulCancel"
          />
        </template>
        <fixed-pagination v-show="list.total > 0" class="bottom-pagination">
          <div class="delete-button-container">
            <el-button :disabled="btnDisabled" size="small" type="primary" class="related-btn" @click="confirmRelatedOrder">关联订单</el-button>
            <el-button size="small" plain type="primary" class="related-btn" @click="onBackClick">返回</el-button>
          </div>
          <el-pagination
            v-show="showPagination"
            :current-page="list.page"
            :page-size="list.perPage"
            :total="list.total"
            :page-sizes="[20, 50, 100, 250, 500]"
            :pager-count="5"
            layout="total, prev, pager, next, sizes,jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
        </fixed-pagination>
      </div>
    </div>
  </el-drawer>
</template>

<script>
import { getList as getChannelOrders } from '@/api/order';
import { getProjectChildOrder, getList as getProjectOrders } from '@/api/project';
import FilterInput from '@/components/Tool/filter';
import channelOrder from './orderList/channelOrder';
import ProjectChannelOrder from './orderList/projectChannelOrder';
import ProjectOrder from './orderList/projectOrder';
import RelatedOrders from './mixins/relatedOrders';
import { ACTIVE_ORDERS, SUB_ACTIVE_ORDERS } from '@/utils/const/order';
import { paramsRangeFormat } from '@/utils/paramsFormat';
import { mapState } from 'vuex';
export default {
  name: 'RelatedOrders',
  components: {
    FilterInput,
    channelOrder,
    ProjectChannelOrder,
    ProjectOrder
  },
  mixins: [RelatedOrders],
  props: {
    isExcludeOrderMode: { // 是否需要排除最终单和对冲单
      type: Boolean,
      default: true
    },
    exceptReviewStatus: { // 待复审状态的订单是否禁止关联发票合同
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      ACTIVE_ORDERS,
      SUB_ACTIVE_ORDERS,
      paramsObj: {},
      page: 1,
      perPage: 20,
      list: {
        items: [],
        page: 1,
        perPage: 20,
        total: 0
      },
      selectedData: {
        channelTable: [], // 渠道订单
        projectChannelTable: [], // 项目渠道订单
        projectTable: [] // 项目订单
      },
      listLoading: true,
      rangeKeyArr: [{
        attr: 'approvalTime',
        start: 'projectApprovalStart',
        end: 'projectApprovalEnd',
        type: 'time'
      }, {
        attr: 'finishTime',
        start: 'finishStart',
        end: 'finishEnd',
        type: 'time'
      }, {
        attr: 'createTime',
        start: 'createStart',
        end: 'createEnd',
        type: 'time'
      }],
      btnDisabled: false
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    })
  },
  methods: {
    init() {
      this.queryOrderList(true);
      this.$nextTick(() => {
        this.setOrderSelectedRows();
      });
    },
    resetData() {
      this.paramsObj = {};
      this.sortName = '';
      this.sortType = '';
      this.list.items = [];
    },
    // 格式化各个列表的入参
    formatParams() {
      const params = JSON.parse(JSON.stringify(this.paramsObj));
      /* if (params.taxAmount && params.taxAmount.length === 2) {
        params.taxAmountStart = params.taxAmount[0] || params.taxAmount[0] === 0 ? (Number(params.taxAmount[0]).toFixed(2) * 100).toFixed(0) : null;
        params.taxAmountEnd = params.taxAmount[1] || params.taxAmount[1] === 0 ? (Number(params.taxAmount[1]).toFixed(2) * 100).toFixed(0) : null;
      }
      delete params.taxAmount; */
      paramsRangeFormat([{
        attr: 'taxAmount',
        start: 'taxAmountStart',
        end: 'taxAmountEnd',
        type: 'moneyFixed'
      }], params);
      switch (this.curActiveOrder) {
        case ACTIVE_ORDERS.CHANNEL:
        case ACTIVE_ORDERS.PROJECT_CHANNEL:
          // 时间处理
          /* if (params.orderTime && params.orderTime.length === 2) {
            params.orderStartTime = Math.round(params.orderTime[0] / 1000);
            params.orderEndTime = Math.round(params.orderTime[1] / 1000);
          }
          delete params.orderTime; */
          paramsRangeFormat([{
            attr: 'orderTime',
            start: 'orderStartTime',
            end: 'orderEndTime',
            type: 'time'
          }], params);
          if (params.accountBelong && typeof params.accountBelong !== 'string' && params.accountBelong.length > 0) {
            params.accountBelong = params.accountBelong.join(',');
          }
          params.sortName = this.sortName || '';
          params.sortType = this.sortType || '';
          if (this.isExcludeOrderMode) {
            params.excludeFinalOrder = true; // 排除最终单和对冲单
          } else {
            params.orderMode = 0;
          }
          break;
        case ACTIVE_ORDERS.PROJECT:
          /* if (params.approvalTime && params.approvalTime.length === 2) {
            params.projectApprovalStart = Math.round(params.approvalTime[0] / 1000);
            params.projectApprovalEnd = Math.round(params.approvalTime[1] / 1000);
          }
          if (params.finishTime && params.finishTime.length === 2) {
            params.finishStart = Math.round(params.finishTime[0] / 1000);
            params.finishEnd = Math.round(params.finishTime[1] / 1000);
          }
          if (params.createTime && params.createTime.length === 2) {
            params.createStart = Math.round(params.createTime[0] / 1000);
            params.createEnd = Math.round(params.createTime[1] / 1000);
          }
          delete params.approvalTime;
          delete params.finishTime;
          delete params.createTime; */
          paramsRangeFormat(this.rangeKeyArr, params);
          params.sortName = this.sortName;
          params.sortType = this.sortType;
          params.exceptReviewStatus = this.exceptReviewStatus; // 待复审状态的订单禁止关联发票合同，需要过滤
          break;
      }
      params.page = this.page;
      params.perPage = this.perPage;
      return params;
    },
    // 获取列表数据
    async queryOrderList(reset = false, noLoading = false, ids = '') {
      reset && (this.page = 1);
      if (!noLoading) this.listLoading = true;
      const params = this.formatParams();
      ids && (params.ids = ids);
      this.listLoading = true;
      await this.queryOrderCallback(params);
    },
    // 各列表调用接口
    async queryOrderCallback(params) {
      switch (this.curActiveOrder) {
        case ACTIVE_ORDERS.PROJECT_CHANNEL:
          try {
            const result = await getProjectChildOrder(params);
            this.list = result && result.data;
            this.listLoading = false;
          } catch (e) {
            this.listLoading = false;
          }
          break;
        case ACTIVE_ORDERS.PROJECT:
          try {
            const result = await getProjectOrders(params);
            const data = result && result.data;
            data && data.items.map(item => {
              if (item.department && item.department.length) item.departmentName = item.department.map(i => i.name).join(',');
              if (item.cooperation && item.cooperation.length) item.cooperationName = item.cooperation.map(i => i.userName).join(',');
              return item;
            });
            this.list = data;
            this.listLoading = false;
          } catch (e) {
            this.listLoading = false;
          }
          break;
        default:
          try {
            const result = await getChannelOrders(this.page, this.list.perPage, params);
            const data = result && result.data;
            data && data.items.map(item => { // 添加订单类型的icon,颜色
              const typeImg = this.orderTypeImg.find(currentValue => item.orderType === currentValue.type);
              const reviewState = this.reviewState.find(currentValue => item.reviewState === currentValue.status);
              if (item.orderInfo.orderKind && item.orderInfo.orderKind.length) item.orderInfo.orderKindName = item.orderInfo.orderKind.map(i => i.orderKindName).join('，');
              item = Object.assign(item, typeImg, reviewState);
              return item;
            });
            this.list = data;
            this.listLoading = false;
          } catch (e) {
            this.listLoading = false;
          }
          break;
      }
    },
    // 项目订单列表排序
    projectOrderSort(data) {
      if (!data.order) {
        this.sortName = '';
        this.sortType = '';
      } else {
        switch (data.prop) {
          case 'taxAmount':
            this.sortName = 'tax_included_amount';
            break;
          case 'costAmount':
            this.sortName = 'cost';
            break;
          case 'projectApprovalDate':
            this.sortName = 'start_project_date';
            break;
          case 'receivePayDate':
            this.sortName = 'receive_payment_date';
            break;
          case 'createDate':
            this.sortName = 'create_date';
            break;
        }
        this.sortType = data.order === 'ascending' ? 1 : -1;
      }
      this.queryOrderList();
    },
    // 切换订单tab
    onOrderChange() {
      this.resetData();
      this.handleActiveOrderChange(this.curSubActiveOrder);
      this.$nextTick(() => {
        this.$refs['FilterToolRef'].changeSelectKey();
      });
    },
    // 切换列表tab
    onSubActiveOrderChange(data) {
      this.handleActiveOrderChange(data.paneName);
    },
    // 订单列表 -> 直接获取数据，已选中订单 -> 根据id获取数据
    async handleActiveOrderChange(val) {
      if (this.listLoading) return;
      if (val === SUB_ACTIVE_ORDERS.ALL_ORDER) {
        await this.queryOrderList(true);
        this.setOrderSelectedRows();
      } else {
        const ids = this.getCurSelectedIds();
        if (!ids) {
          this.list.items = [];
          this.listLoading = false;
          return;
        }
        await this.queryOrderList(true, false, ids);
        this.setOrderSelectedRows();
      }
    },
    setOrderSelectedRows() {
      const { channelTable, projectChannelTable, projectTable } = this.selectedData;
      switch (this.curActiveOrder) {
        case ACTIVE_ORDERS.CHANNEL:
          this.$refs['channelOrder'].multipleSelectionAll = channelTable;
          break;
        case ACTIVE_ORDERS.PROJECT_CHANNEL:
          this.$refs['projectChannelOrder'].multipleSelectionAll = projectChannelTable;
          break;
        case ACTIVE_ORDERS.PROJECT:
          this.$refs['projectOrder'].multipleSelectionAll = projectTable;
          break;
      }
    },
    // 获取选中列表订单的id值
    getCurSelectedIds() {
      let ids = [];
      const { channelTable, projectChannelTable, projectTable } = this.selectedData;
      switch (this.curActiveOrder) {
        case ACTIVE_ORDERS.CHANNEL:
          ids = channelTable.map(item => item.relatedId || item.id);
          break;
        case ACTIVE_ORDERS.PROJECT_CHANNEL:
          ids = projectChannelTable.map(item => item.relatedId || item.id);
          break;
        case ACTIVE_ORDERS.PROJECT:
          ids = projectTable.map(item => item.relatedId || item.id);
          break;
      }
      return ids.join(',');
    },
    handleFilterInputChange({ value, item }) {
      if (item.keyword === 'orderPlatformId') {
        this.$set(this.paramsObj, 'orderFormId', '');
      }
    },
    queryClick() {
      this.handlePaginationOption(true);
    },
    queryEmpty() {
      this.resetData();
      this.handlePaginationOption(true);
    },
    // 保存选中的订单数据
    onSelectChange(name, data) {
      this.selectedData[name] = data;
    },
    // 取消关联
    relatedCancel(rowData) {
      const { channelTable, projectChannelTable, projectTable } = this.selectedData;
      const listIndex = this.list.items.findIndex(item => item.id === rowData.id);
      this.list.items.splice(listIndex, 1);
      let index = -1;
      switch (this.curActiveOrder) {
        case ACTIVE_ORDERS.CHANNEL:
          index = channelTable.findIndex(item => item.id === rowData.id || item.relatedId === rowData.id);
          index !== -1 && channelTable.splice(index, 1);
          break;
        case ACTIVE_ORDERS.PROJECT_CHANNEL:
          index = projectChannelTable.findIndex(item => item.id === rowData.id || item.relatedId === rowData.id);
          index !== -1 && projectChannelTable.splice(index, 1);
          break;
        case ACTIVE_ORDERS.PROJECT:
          index = projectTable.findIndex(item => item.id === rowData.id || item.relatedId === rowData.id);
          index !== -1 && projectTable.splice(index, 1);
          break;
      }
    },
    // 多选取消关联
    relatedMulCancel() {
      switch (this.curActiveOrder) {
        case ACTIVE_ORDERS.CHANNEL:
          this.selectedData['channelTable'] = [];
          break;
        case ACTIVE_ORDERS.PROJECT_CHANNEL:
          this.selectedData['projectChannelTable'] = [];
          break;
        case ACTIVE_ORDERS.PROJECT:
          this.selectedData['projectTable'] = [];
          break;
      }
      this.list.items = [];
    },
    handleSizeChange(val) {
      this.perPage = val;
      this.handlePaginationOption(true);
      this.$nextTick(() => {
        document.body.scrollTop = document.documentElement.scrollTop = 0;
      });
    },
    handleCurrentChange(toPage) {
      this.page = toPage;
      this.handlePaginationOption();
      this.$nextTick(() => {
        document.body.scrollTop = document.documentElement.scrollTop = 0;
      });
    },
    handlePaginationOption(reset = false) {
      const isSubTab = this.curSubActiveOrder === SUB_ACTIVE_ORDERS.CHECKED_ORDER;
      if (!isSubTab) {
        this.queryOrderList(reset);
      } else {
        const ids = isSubTab && this.getCurSelectedIds();
        if (!ids) {
          this.list.items = [];
          this.listLoading = false;
        } else {
          this.queryOrderList(reset, false, ids);
        }
      }
    },
    confirmRelatedOrder() {
      this.btnDisabled = true;
      const _this = this;
      setTimeout(function() {
        _this.$emit('confirmRelatedOrder', _this.selectedData);
        _this.btnDisabled = false;
      }, 1000);
    },
    onBackClick() {
      this.onDrawerClosed();
      this.$emit('onBack');
    }
  }
};
</script>

<style scoped lang="scss">
::v-deep .el-drawer {
  min-width: 300px;
}
::v-deep .el-badge__content {
  display: flex;
  align-items: center;
}
::v-deep .el-tabs__header {
  border-bottom: none;
}
.related-order-drawer {
  ::v-deep .el-drawer__header {
    height: 48px;
    padding: 0 12px 0 24px;
    margin: 0;
    box-shadow: 2px 4px 5px 0 rgba(221,225,234,0.3);
    display: flex;
    align-items: center;
    overflow-x: auto;
    > span {
      font-size: 14px;
      color: #333;
    }
    ::v-deep .el-tabs__nav-wrap::after {
      height: 0 !important;
    }
  }
  ::v-deep .el-tabs__header {
    margin: 0;
  }
  ::v-deep .el-drawer__body {
    overflow-y: auto;
    margin-bottom: 56px;
  }
  .drawer-content {
    padding: 22px 24px 0;
    overflow-y: auto;
    .table-list {
      border-radius: 10px;
      .el-row {
        padding: 0;
      }
      .delete-button-container {
        flex:1;
        height: 32px;
        display: flex;
        align-items: center;
        .related-btn {
          margin-left: 20px;
          padding-left: 12px;
          padding-right: 12px;
        }
      }
      ::v-deep .pagination-flex {
        position: absolute;
        width: 100% !important;
      }
    }
    .tab-content {
      margin: 17px 0 8px;
      &::v-deep {
        .el-tabs__header  {
          margin-bottom: 0 !important;
          border-bottom: 1px solid #ddd;
          .el-tabs__nav {
            border: none !important;
          }
          .el-tabs__item {
            padding: 0 12px !important;
            height: 32px !important;
            line-height: 32px !important;
            margin-right: 8px;
            border: 1px solid #ddd;
            border-radius: 4px 4px 0px 0px;
            color: #333;
            background: #f7f8fa;
            font-size: 16px;
            &:last-child {
              margin-right: 0px;
            }
            &.is-active {
              border-bottom-color: #FFFFFF !important;
              font-weight: bold;
              background: #fff;
              color: #406eff;
            }
          }
        }
        .el-badge__content{
          background: #FB5227;
          transform: translateY(5px);
        }
      }
    }
  }
  ::v-deep .related-order-tabs {
    .el-tabs__header {
      .el-tabs__active-bar {
        display: none;
      }
      .el-tabs__nav-wrap::after {
        display: none;
      }
    }
    .el-tabs__item {
      font-size: 16px;
    }
  }
}
::v-deep .pagination-flex {
  overflow-x: auto;
  bottom: 0;
}
::v-deep .el-tabs__nav-wrap::after {
  z-index: -1;
}
::v-deep .el-tabs__active-bar {
  bottom: 1px;
}
</style>
